package com.ctw.mapmycity.hbase.controller;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.util.Bytes;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.hadoop.hbase.HbaseTemplate;
import org.springframework.stereotype.Component;

import com.ctw.mapmycity.hbase.repository.AccountRepository;
import com.ctw.mapmycity.model.Account;

@Component
public class AccountController implements InitializingBean {
	
	private String tableName = "posts";
	private byte[] tableNameAsBytes = Bytes.toBytes(tableName);

	@Resource(name = "hbaseConfiguration")
	private Configuration config;

	@Autowired
	private HbaseTemplate hbaseTemplate;

	@Autowired
	private AccountRepository accRepository;

	private HBaseAdmin admin;

	public void initialize() throws IOException {

		if (admin.tableExists(tableNameAsBytes)) {
			return;
//			if (!admin.isTableDisabled(tableNameAsBytes)) {
//				System.out.printf("Disabling %s\n", tableName);
//				admin.disableTable(tableNameAsBytes);
//			}
//			System.out.printf("Deleting %s\n", tableName);
//			admin.deleteTable(tableNameAsBytes);
		}

		HTableDescriptor tableDescriptor = new HTableDescriptor(tableName);
		HColumnDescriptor columnDescriptor = new HColumnDescriptor(AccountRepository.CF_INFO);
		tableDescriptor.addFamily(columnDescriptor);

		admin.createTable(tableDescriptor);

	}

	public void saveAccount(Account acc) {
		accRepository.save(acc);
//		acc = accRepository.get(acc.getEmail());
	}
	
	public Account getAccount(String email) {
		return accRepository.get(email);
	}
	
	
	public void deleteAccount(String email) {
		accRepository.delete(email);
	}

	public List<Account> findAllAccounts() {
		return accRepository.findAll();
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		admin = new HBaseAdmin(config);
	}
}